package com.uinfor.controller;

import com.uinfor.entity.Payment;
import com.uinfor.entity.Result;
import com.uinfor.service.IPaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @descripttion:
 * @Author: WZH
 * @Date :2021/1/18  9:54
 **/
@RestController
@Slf4j
public class PaymentController {
    @Autowired
    private IPaymentService paymentService;
    @Value("${server.port}")
    private String serverPort;
    @Resource
    private DiscoveryClient discoveryClient;
    @PostMapping(value = "/payment/create")
    public Result create(@RequestBody Payment payment){
        log.info(payment.getSerial());
        int i = paymentService.create(payment);
        log.info("****************插入结果"+i+serverPort);
        Result<Object> result = new Result<>();
        if (i>0){
            result.setCode(200);
            result.setMessage("插入成功"+serverPort);
        }else {
            result.setCode(444);
        }
        return result;
    }
    @GetMapping(value = "/payment/get/{id}")
    public Result getPaymentById(@PathVariable("id")Long id){
        Payment paymentById = paymentService.getPaymentById(id);
        log.info("****************查询结果是"+paymentById.toString()+serverPort);
        Result<Object> result = new Result<>();
        if (!"".equals(paymentById.getId())){
            result.setCode(200);
            result.setMessage("查询成功"+serverPort);
            result.setData(paymentById);
        }else {
            result.setCode(444);
            result.setMessage("查询失败");
        }
        return result;
    }
    @GetMapping("/payment/discovery")
    public Object discovery(){
        List<String> services = discoveryClient.getServices();
        for (String i:services){
            log.info("*******element"+i);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVER");
        for (ServiceInstance i:instances){
            log.info(i.getServiceId()+"\t"+i.getHost()+"\t"+i.getPort()+"\t"+i.getUri());
        }
        return this.discoveryClient;
    }
    @GetMapping("/payment/lb")
    public String getPaymentLb(){
        return serverPort;
    }
    @GetMapping("/payment/timeout")
    public String payMentFeignTimeOut(){
        try{
            TimeUnit.SECONDS.sleep(3);
        }catch (Exception e){
            e.printStackTrace();
        }
        return serverPort;
    }
    @GetMapping("/payment/zipkin")
    public String paymentZipkin(){
        return " i am zipkin server fall back !(∩_∩)O哈哈~";
    }
}
